package cn.jiyun.filter;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.nacos.api.utils.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: 小周
 * @Package: cn.jiyun.filter
 * @Project: p11_parent
 * @name: MyFilter
 * @Date: 2023/7/31 16:47
 * @Filename: MyFilter
 */
@Component
public class MyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        String loginPageUrl="/adminUser/login";
        System.out.println("+++++++++++++++++++执行网关");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        System.out.println("+++++++++++++url:"+path);
        if (path.contains("/login") || path.contains(".html") || path.contains(".js") || path.contains(".css") ) return chain.filter(exchange);

            //先获取token  看之前是否登录过
            String token=getToken(request);
            if (!StringUtils.isBlank(token)){
                try {
                    //不为空的话 判断token是否正确 是否过期
                    boolean verify = JWTUtil.verify(token, "zhou".getBytes());
                    if (verify){
                        //token正常  放行
                        return chain.filter(exchange);
                    }else{
                        //过期  返回401
                        response.setStatusCode(HttpStatus.UNAUTHORIZED);
                        return response.setComplete();
                    }
                }catch (Exception e){
                    //异常 返回401
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
            }

        //token为空  证明之前没有登录过  重定向到登录页面
        //给前台返回401状态码  其他的交给前台去处理
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();


    }

    @Override
    public int getOrder() {
        return 1;
    }
    public String getToken(ServerHttpRequest request){
        return request.getHeaders().getFirst("token");
    }
}